package vip.xiaonuo.biz.modular.inventorycheck.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import org.apache.poi.ss.usermodel.Workbook;
import vip.xiaonuo.biz.modular.inventorycheck.vo.ReportExcelExportGoodsVO;
import vip.xiaonuo.biz.modular.inventorycheck.vo.ReportExcelExportReagentVO;
import vip.xiaonuo.common.util.CommonDownloadUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ReportExcelExporter {
    public static void generateExcelForGoods(HttpServletResponse response, List<ReportExcelExportGoodsVO> dataList) throws IOException {
        String fileName = String.format("物品扫码盘库报告%s", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(fileName, "报告明细"), ReportExcelExportGoodsVO.class, dataList);
        generateExcel(response, fileName, workbook);
    }


    public static void generateExcelForReagent(HttpServletResponse response, List<ReportExcelExportReagentVO> dataList) throws IOException {
        String fileName = String.format("试剂扫码盘库报告%s", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(fileName, "报告明细"),
                 ReportExcelExportReagentVO.class, dataList);
        generateExcel(response, fileName, workbook);
    }

    private static void generateExcel(HttpServletResponse response, String fileName, Workbook workbook) throws IOException {
        File tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName + ".xls");
        if (FileUtil.exist(tempFile)) FileUtil.del(tempFile);
        BufferedOutputStream outputStream = FileUtil.getOutputStream(tempFile);
        workbook.write(outputStream);
        outputStream.close();
        if (response != null) CommonDownloadUtil.download(tempFile, response);
    }

    public static void main(String[] args) throws IOException {
        List<ReportExcelExportGoodsVO> dataList = new ArrayList<>();
        ReportExcelExportGoodsVO vo = new ReportExcelExportGoodsVO();
        vo.setCreateTime(new Date());
        dataList.add(vo);
        ReportExcelExporter.generateExcelForGoods(null, dataList);
    }
}
